package cn.git.shiro.test;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource;

/**
 * @description: 自定义登录认证
 * @program: bank-credit-sy
 * @author: lixuchun
 * @create: 2024-03-26
 */
public class CustomRealm extends AuthenticatingRealm {

    /**
     * 自定义登录认证方法
     * subject.login()会调用此方法，需要配置自定义realm生效，在ini文件中配置，或者在springboot中配置，
     * 该方法只是获取进行对比的信息，认证逻辑还是按照shiro的认证逻辑完成
     *
     * @param token 登录token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 1.获取身份信息
        String principal = token.getPrincipal().toString();

        // 2.获取凭证信息
        String password = new String((char[]) token.getCredentials());
        System.out.println("principal:" + principal + " password:" + password);

        // 3.获取数据库中存储的凭证信息
        if (principal.equals("zhangsan")) {
            // 获取数据库加盐3次加密密码
            String dbPassword = "3e2c6b7df0d3106109c74663d887df3b";
            // 创建封装逻辑校验对象
            AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                    token.getPrincipal(),
                    dbPassword,
                    ByteSource.Util.bytes("3313"),
                    principal);
            return authenticationInfo;
        }

        return null;
    }
}
